const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const koaBody = require('koa-body')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')

const config = require('./config')
const routes = require('./routes')

const port = process.env.PORT || config.port

const mysql = require('mysql2');
// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test',
  password: 'wyd521',
  charset: 'utf8mb4'
});
 
// simple query
connection.query(
  'SELECT * FROM `mytable` WHERE `sex` = 0',
  function(err, results, fields) {
    // console.log(results); // results contains rows returned by server
  }
);

// error handler
onerror(app)

// middlewares
app
  .use(koaBody({
    multipart: true,
    formidable: {
      uploadDir: path.join(__dirname, '/public/upload'),
      keepExtensions: true,
      maxFieldsSize: 2*1024*1024*1024
    }
  }))
  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: {settings: {views: path.join(__dirname, 'views')}},
    map: {'hjs': 'hogan'},
    extension: 'hjs'
  }))
  .use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*')
    ctx.set('Access-Control-Allow-Methods', 'OPTIONS, PUT, GET, POST, DELETE')
    await next()
  })
  .use(router.routes())
  .use(router.allowedMethods())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - $ms`)
})

app.use(routes.routes())
app.on('error', function(err, ctx) {
  console.log(err)
  logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
